#include <iostream>
#include "../tcp/Socket.h"
#include "../tcp/SocketUtils.h"
#include "../base/log/Logging.h"
#include "unistd.h"
#include "../tcp/InetAddress.h"
#include "../tcp/Connector.h"
#include "../tcp/Poller.h"
#include "../tcp/EventLoopThreadPool.h"
#include "../tcp/EventLoop.h"
#include "../tcp/Channel.h"

#define SERVER_IP "175,178,51,126"
#define SERVER_PORT 8200

typedef std::function<void()> EventCallback;
typedef std::function<void(Timestamp)> ReadEventCallback;

int serverfd = -1;

void onReadCallback(Timestamp timestamp) {
    assert(serverfd != -1);
    char buf[BUFSIZ];
    sockets::read(serverfd, buf, BUFSIZ);
    InetAddress addr(Socket::getPeerAddr(serverfd));
    fprintf(stderr, "接收到来自服务器(%s : %d)的消息 : %s", addr.toIp().c_str(), addr.toPort(), buf);
}

void onWriteCallback() {
    assert(serverfd != -1);
    string message;
    std::cin >> message;
    write(serverfd, message.c_str(), message.size());
}


int main() {
    InetAddress serverAddr(SERVER_IP, SERVER_PORT);
    Socket socket_(sockets::createNonblockingOrDie(serverAddr.family()));
    // 创建文件描述符

    assert(sockets::connect(socket_.fd(), serverAddr.getSockAddr()) != 0);
    serverfd = socket_.fd();
    EventLoop loop;
    // 创建连接
    EventLoopThreadPool pool(&loop, "mainThread");
    pool.setThreadNum(1);
    pool.start();
    Channel channel(&loop, socket_.fd());
    channel.setReadCallback(onReadCallback);
    channel.enableReading();
    // 将文件描述符套入
    Channel writeChannel(pool.getNextLoop(), socket_.fd());
    channel.setWriteCallback(onWriteCallback);
    channel.enableWriting();
    loop.loop();
    return 0;
}

/*int main() {
    std::string message = "测试下";

    Socket socket_(socket(AF_INET, SOCK_STREAM, 0));
    InetAddress serverAddr("175.178.51.126", SERVER_PORT);

    std::cout << "准备连接" << std::endl;

    if(connect(socket_.fd(), serverAddr.getSockAddr(), sizeof(* serverAddr.getSockAddr())) == -1){
        std::cout << "结束" << std::endl;
    }else{
        write(socket_.fd(), message.c_str(), message.size());
        char buf[BUFSIZ];
        read(socket_.fd(), &buf, sizeof buf);
        std::cout << "收到的信息为 : " << buf << std::endl;
        close(socket_.fd());
    }

    std::cout << "Hello, World!" << std::endl;
    return 0;
}*/
